/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.export.tolerance;

import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.foundation.poi.ExCell;
import com.intelligent.ispc.foundation.poi.ExCellFactory;
import com.intelligent.ispc.foundation.poi.ExSheet;
import com.intelligent.ispc.foundation.poi.SampleExcelBuilder;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by cherry on 2016/9/21.
 */
public class TolExcelBuilder extends SampleExcelBuilder {
    private static Logger logger = LoggerFactory.getLogger(TolExcelBuilder.class);
    private int size = 0;

    public TolExcelBuilder() {
    }

    @Override
    public void drawExcel(String path, ExCellFactory factory) {
        XSSFWorkbook workbook = factory.getCurrentWorkbook();
        List<ExSheet> sheets = factory.getSheets();
        try {
            OutputStream out = new FileOutputStream(path);
            size = sheets.size();
            for (int i = 0; i < size; i++) {
                drawTolSheet(workbook, sheets.get(i));
            }
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            logger.error("can not find directory:" + e);
            throw new ApplicationException(e.getMessage());
        }
    }

    private void drawTolSheet (XSSFWorkbook workbook, ExSheet exSheet) {
        String name = exSheet.getName();
        logger.debug("sheet name:{}", name);
        List<ExCell> exCells = exSheet.getExCells();
        XSSFSheet sheet = workbook.createSheet(name);
        sheet.setDefaultColumnWidth(20);
        drawSheet(exCells, sheet, workbook);
    }
}
